package com.ac.exception;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ac.model.LogSystem;
import com.ac.model.LogSystemType;
import com.ac.response.HttpStatus;
import com.ac.response.Res;
import com.ac.util.IPUtils;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import ch.qos.logback.classic.Logger;

/**
 * 对象转换异常
 */
@Component
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class InvalidFormatExceptionHandler {

	public static final Logger logger = (Logger) LoggerFactory.getLogger(InvalidFormatExceptionHandler.class);

	@PostConstruct
	public void init() {
	}

	@ExceptionHandler(InvalidFormatException.class)
	@ResponseBody
	public Res BindExceptionHandlerFun(HttpServletRequest request, InvalidFormatException e) {
		String ipAddr = IPUtils.getIpAddr(request);
		String url = ExceptionService.getApiUrl(request);

		LogSystem logSystem = new LogSystem();

		String _et = ExceptionService.exceptionToString(e);
		String title = "转换异常";
		Pattern pattern = Pattern.compile("\\[\\\"([^\\\"]+)\\\"\\]");
		Matcher matcher = pattern.matcher(_et);
		if (matcher.find()) {
			String type = matcher.group(1);
			title = "字段【" +type +"】" + title;
		}
		logSystem.setTitle(title);
		logSystem.setIp(ipAddr);
		logSystem.setType(LogSystemType.Method);
		logSystem.setContent(url + "-----" + _et);
		logSystem.setCode(HttpStatus.BAD_REQUEST);
		ExceptionService.addLogSystem(logSystem);
		return new Res(HttpStatus.BAD_REQUEST, title);
	}

}
